<template>
  <div class="dashboard-container">
    <div class="app-container">
      <h2>
        <el-card class="tree-card">
          <TreeTool :data="company">
            <el-dropdown-item>添加子部门</el-dropdown-item>
          </TreeTool>
          <el-tree v-loading="isLoading" :data="list" :props="{label: 'name', childern: 'children'}" default-expand-all>
            <template v-slot="{data}">
              <TreeTool :data="data">
                <!-- el-dropdown-item组件通信,支持click时间吗?不支持 -->
                <el-dropdown-item @click.native="onAdd(data)">添加子部门</el-dropdown-item>
                <el-dropdown-item @click.native="onEdit(data)">编辑部门</el-dropdown-item>
                <el-dropdown-item @click.native="onDel(data.id)">删除部分</el-dropdown-item>
              </TreeTool>
            </template>
          </el-tree>
        </el-card>
      </h2>
    </div>

    <AddDept ref="addDeptRef" :visible.sync="showDialog" :node="currentNode" @success="getList" />
  </div>
</template>

<script>
import { delDept, getDeptByid, getList } from '@/api/departments.js'
import TreeTool from './components/treeTool.vue'
import { translateListToTree } from '@/utils/index.js'
import AddDept from './components/addDept.vue'
export default {
  name: 'Department',
  components: {
    TreeTool,
    AddDept
  },
  data() {
    return {
      isLoading: false, // 加载状态
      showDialog: false, // 控制添加部门弹框显示
      company: { name: '传智教育', manager: '负责人' }, // 定义公司的数据
      list: [],
      currentNode: {} // 当前操作的部门
    }
  },
  computed: {

  },
  created() {
    this.getList()
  },
  methods: {
    // 获取部门列表数据
    async getList() {
      this.isLoading = true
      const { companyName, depts } = await getList()
      this.company.name = companyName
      this.list = translateListToTree(depts, '')
      this.isLoading = false
    },
    // 添加子部门
    onAdd(node) {
      this.currentNode = node
      this.showDialog = true
    },
    // 编辑部门
    async onEdit(node) {
      this.currentNode = node
      /* 父传子
      方式1 - props(不推荐,改动太大)
      方式2 - ref(推荐) */
      this.showDialog = true
      // 获取子组件中的数据并修改它, 改变里子组件form的初始值
      this.$refs.addDeptRef.form = await getDeptByid(node.id)
    },
    // 删除部门
    onDel(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delDept(id)
        this.getList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
  font-weight: normal;
}
// .el-dropdown-link {
//   margin-left: 10px;
// }
</style>
